package com.cheney.common.sensitive.core;

import com.cheney.common.sensitive.strategy.SensitiveStrategy;
import com.cheney.common.sensitive.util.SensitiveUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;

import java.util.HashSet;
import java.util.Set;

import static com.cheney.common.sensitive.constant.SensitiveConstant.ENUM_SPLIT_SIGN;

/**
 * Strategy转换器
 */
public class SensitiveStrategyConverter implements GenericConverter {

    private final ApplicationContext applicationContext;

    public SensitiveStrategyConverter(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        ConvertiblePair convertiblePair = new ConvertiblePair(String.class, SensitiveStrategy.class);
        Set<ConvertiblePair> convertiblePairSet = new HashSet<>(1);
        convertiblePairSet.add(convertiblePair);
        return convertiblePairSet;
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        String sourceStr = String.valueOf(source);
        try {
            // 枚举类
            if (StringUtils.isNotBlank(sourceStr) && sourceStr.contains(ENUM_SPLIT_SIGN)) {
                int asSignIndex = sourceStr.indexOf(ENUM_SPLIT_SIGN);
                return SensitiveUtil.checkAndGetEnumInstance(sourceStr.substring(0, asSignIndex),
                        sourceStr.substring(asSignIndex + ENUM_SPLIT_SIGN.length()));
            }
            // 普通类
            return SensitiveUtil.checkAndGetInstance(sourceStr, SensitiveStrategy.class, applicationContext);
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            throw new IllegalArgumentException("convert source[" + sourceStr + "] to DesensitizationStrategy Exception!", e);
        }
    }
}
